package com.inspector.app.ui.base

import android.app.Application
import com.alibaba.fastjson.JSON
import com.example.commen.base.UCApplication
import com.example.commen.net.easyHttp.model.RequestHandler
import com.example.commen.net.easyHttp.server.ReleaseServer
import com.example.commen.resource.CommentContect
import com.example.commen.resource.HttpContect
import com.example.commen.utile.CommonUtils
import com.hjq.http.EasyConfig
import com.hjq.http.config.IRequestInterceptor
import com.hjq.http.config.IRequestServer
import com.hjq.http.model.HttpHeaders
import com.hjq.http.model.HttpParams
import com.hjq.http.request.HttpRequest
import com.inspector.app.BaseApp
import com.inspector.app.BuildConfig
import com.inspector.app.di.network.api.LoginInfo
import com.inspector.app.di.network.api.MenuTreeApi
import com.inspector.app.di.network.api.SmsloginApi
import com.inspector.app.di.network.api.UserInfoApi
import com.inspector.app.di.network.api.getLoginPasswordApi
import com.inspector.app.di.network.api.getSmsLoginCodeApi
import com.inspector.app.util.CommenArgs
import com.inspector.app.util.SharedPreferencesUtils
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit

fun initLoginInfo() {
    val info = SharedPreferencesUtils.getString(CommentContect.SpConstant.LoginInfo)
    if (info != null) {
        CommenArgs.loginInfo = JSON.parseObject(info, LoginInfo::class.java)
    }
}

fun initUserinfo() {
    initLoginInfo()
    if (CommenArgs.userInfo == null) {
        val userInfos = SharedPreferencesUtils.getString(CommentContect.SpConstant.UserInfo)
        CommenArgs.userInfo = JSON.parseObject(userInfos, UserInfoApi.UserInfo::class.java)
        if (CommenArgs.userInfo == null) {
            CommenArgs.userInfo = UserInfoApi().initUserinfo()
        } else {
            if (CommenArgs.loginInfo.token.isNotEmpty()
            ) {
                CommenArgs.setIsLogin(true)
            } else {
                BaseApp.getInstance().loginOut()
            }
        }
    }
}

fun initMenuTree() {
    val dat = SharedPreferencesUtils.getString(CommentContect.SpConstant.MenuTree)
    if ((CommenArgs.Trees.menuTree.isEmpty() || CommenArgs.Trees.MyTree.MyMenuTree.isEmpty()) && dat != null) {
        val array = JSON.parseArray(dat, MenuTreeApi.MenuTrueInfoData::class.java)
        setMenuTreeData(array)
    }
}

fun setMenuTreeData(data: MutableList<MenuTreeApi.MenuTrueInfoData>) {
    /**底部导航-我的*/
    CommenArgs.Trees.menuTree = data
    var mylist = data.filter { it.alias == "my" }.filter { it.showType != 2 }
    if (mylist.isNotEmpty()) {
        CommenArgs.Trees.MyTree.MyMenuTree = mylist.first().children
        /**获取我的-个人信息*/
//        var MyMenu_Userinfo = CommenArgs.Trees.MyTree.MyMenuTree
//            .filter { it.alias == CommenArgs.MY_ALIAS.APP_Personal_Data.name }.toMutableList()
//        if (MyMenu_Userinfo.isNotEmpty()) {
//            CommenArgs.Trees.MyTree.MyMenu_Userinfo = MyMenu_Userinfo.first().children
//                .filter { it.showType != 2 }
//                .toMutableList()
//        }
//        /**获取我的-流程项*/
//        var MyMenu_Flow = CommenArgs.Trees.MyTree.MyMenuTree
//            .filter { it.alias == CommenArgs.MY_ALIAS.APP_ProcessItems.name }
//        if (MyMenu_Flow.isNotEmpty()) {
//            CommenArgs.Trees.MyTree.MyMenu_Flow = MyMenu_Flow.first().children
//                .filter { it.showType != 2 }
//                .toMutableList()
//        }
    }

    /**底部导航-首页*/
    var homelist = data.filter { it.alias == "home" }
        .filter { it.showType != 2 }
    if (homelist.isNotEmpty() && homelist.first().children.isNotEmpty()) {
        CommenArgs.Trees.homeTree =
            homelist.first().children.filter { it.showType != 2 }.toMutableList()
    }

    if (CommenArgs.Trees.homeTree.isNotEmpty()) {
        var planList = CommenArgs.Trees.homeTree.filter { it.alias == "飞行计划" }
        if (planList.isNotEmpty()) {
            CommenArgs.Trees.FlyPlanTree =
                planList.first().children.filter { it.alias == "FlightPlan_InstructorCheck" && it.showType != 2 }
                    .toMutableList()
            CommenArgs.Trees.FlyPlanAll_Flying_GroupTree =
                planList.first().children.filter { it.alias == "All_Flying_Group" && it.showType != 2 }
                    .toMutableList()
            CommenArgs.Trees.FlyPlanAll_Flying_BaseTree =
                planList.first().children.filter { it.alias == "Screening_Base" && it.showType != 2 }
                    .toMutableList()

            CommenArgs.Trees.FlyPlan_Aviation_Statistics =
                planList.first().children.filter { it.alias == "Aviation_Statistics" && it.showType != 2 }
                    .toMutableList()
        }
        var flyTaskTreeList = CommenArgs.Trees.homeTree.filter { it.alias == "飞行任务书" }
        if (flyTaskTreeList.isNotEmpty()) {
            CommenArgs.Trees.FlyTask_Flying_Tree =
                flyTaskTreeList.first().children.filter { it.alias == "az_flyTask" && it.showType != 2 }
                    .toMutableList()
            var list =
                flyTaskTreeList.first().children.filter { it.alias == "hw_taskbookpermission" }
            if (list.isNotEmpty()) {
                CommenArgs.Trees.MainTree.isTaskBookBasePermission = list.first().showType == 0
            }
        }
    }


    /**底部导航-添加*/
    var addlist = data.filter { it.alias == "add" }
        .filter { it.showType != 2 }
    if (addlist.isNotEmpty() && addlist.first().children.isNotEmpty()) {
        CommenArgs.Trees.addTree =
            addlist.first().children.filter { it.showType != 2 }.toMutableList()
    }
}

fun initNet(application: Application) {
    // 网络请求框架初始化
    // 由于每个系统的host不同,所以这里的server只防止非空
    val server: IRequestServer
    server = ReleaseServer()

    HttpContect.BASE_URL = server.host

    val okHttpClient = OkHttpClient.Builder()
        .readTimeout(10, TimeUnit.SECONDS)
        .build()
    EasyConfig.with(okHttpClient)
        // 是否打印日志
        .setLogEnabled(BuildConfig.DEBUG)
        // 设置服务器配置
        .setServer(server)
        // 设置请求处理策略
        .setHandler(RequestHandler(application))
        // 设置请求参数拦截器
        .setInterceptor(object : IRequestInterceptor {
            override fun interceptArguments(
                httpRequest: HttpRequest<*>,
                params: HttpParams,
                headers: HttpHeaders
            ) {
                if (httpRequest.requestApi.api.contains(getSmsLoginCodeApi("").api)
                    || httpRequest.requestApi.api.contains(SmsloginApi("", "").api)
                    || httpRequest.requestApi.api.contains(getLoginPasswordApi("", "").api)
                ) {
                    headers.put("version", CommonUtils.getVersionName(UCApplication.getContext()))
                    //所属应用端，0管理点 1企业端 2app端 3机务web 4机务app
                    headers.put("source", "8")
                } else if (!CommenArgs.loginInfo.token.isNullOrEmpty()) {
                    headers.put("token", CommenArgs.loginInfo.token)
                }
            }
        })
        // 设置请求重试次数
        .setRetryCount(3)
        // 设置请求失败时,再次重试的间隔时间
        .setRetryTime(2000)
        // 添加全局请求参数
//        .addParam("token", "6666666")
        // 添加全局请求头
//        .addHeader("version", CommonUtils.getVersionName(application))
        //所属应用端， 5-app飞行任务
//        .addHeader("source", "8")
        .into()
}
